package com.yanqu.road.server.cmd.tradewar;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.enums.eTradeWarBattleType;
import com.yanqu.road.entity.union.activitygroup.UnionActivityGroup;
import com.yanqu.road.entity.union.activitygroup.UnionActivityGroupUnion;
import com.yanqu.road.entity.union.activitygroup.UnionActivityGroupUser;
import com.yanqu.road.logic.helper.UnionActivityGroupHelper;
import com.yanqu.road.server.cmd.CrossUnionCommand;
import com.yanqu.road.server.manager.union.activitygroup.Cross2UnionActivityGroupMgr;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.pb.cross.tradewar.CrossTradeWarProto;
import com.yanqu.road.server.cmd.CrossCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.tradewar.CrossTradeWarActivityMgr;
import com.yanqu.road.server.manager.tradewar.CrossTradeWarMgr;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.RandomHelper;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

@Cmd(code = Protocol.C_CROSS_TRADE_WAR_PREPARE, desc = "跨服商战匹配")
public class CrossTradeWarPrepareCmd extends CrossUnionCommand {
    private int activityId;
    private int battleType;
    private long myUserId;
    private long myServerId;
    private List<Integer> patronsIdList;
    private long enemyUserId;
    private long enemyServerId;
    private String battleUid;
    private int useItemId;
    private int dailyTrackTimes;
    private int limitTrackTimes;
    private int fastTeamNum = -1;

    private String myUnionId;

    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        CrossTradeWarProto.CrossTradeWarBattleReqMsg reqMsg = CrossTradeWarProto.CrossTradeWarBattleReqMsg.parseFrom(packet.getBytes());
        activityId = reqMsg.getActivityId();
        battleType = reqMsg.getBattleType();
        myUserId = packet.getPlayerId();
        myServerId = serverId;
        patronsIdList = new ArrayList<>(reqMsg.getPatronsIdListList());
        enemyUserId = reqMsg.getEnemyUserId();
        enemyServerId = reqMsg.getEnemyServerId();
        battleUid = reqMsg.getBattleUid();
        useItemId = reqMsg.getUseItemId();
        dailyTrackTimes = reqMsg.getDailyTrackTimes();
        limitTrackTimes = reqMsg.getLimitTrackTimes();
        fastTeamNum = reqMsg.getFastTeamNum();
        myUnionId = reqMsg.getMyUnionId();
        return true;
    }

    @Override
    public void execute(YanQuMessage packet) throws Exception {
        ActivityInfo activityInfo = CrossTradeWarActivityMgr.getActivityInfoIfNotLoadDb(activityId);
        if(null == activityInfo){
            ret = GameErrorCode.E_CROSS_TRADE_WAR_ACTIVITY_NO_FOUND_BATTLE_FAIL;
            return;
        }
        int groupId = Cross2UnionActivityGroupMgr.getGroupId(activityId, myUserId);
        if (groupId == UnionActivityGroupHelper.NO_GROUP_ID){
            ret = GameErrorCode.E_UNION_ACTIVITY_GROUP_NO_ABLE;
            return;
        }
        UnionActivityGroup groupData = Cross2UnionActivityGroupMgr.getGroupData(activityId, groupId);
        if (groupData == null){
            ret = GameErrorCode.E_UNION_ACTIVITY_GROUP_NO_ABLE;
            return;
        }
        long destServerId;
        if(eTradeWarBattleType.RandomBattle.getValue() == battleType){
//            List<Long> serverList = new ArrayList<>();
//            for(long tempServerId : groupData.getServerSet()){
//                if(tempServerId != myServerId){
//                    serverList.add(tempServerId);
//                }
//            }
            List<UnionActivityGroupUser> userList = new ArrayList<>();
            ConcurrentHashMap<String, UnionActivityGroupUnion> unionDataMap = groupData.getUnionDataMap();
            for (UnionActivityGroupUnion union:unionDataMap.values()){
                ConcurrentHashMap<Long, UnionActivityGroupUser> userMap = union.getUserMap();
                if (userMap.containsKey(myUserId)){
                    continue;
                }
                for (UnionActivityGroupUser user:userMap.values()){
                    if (user.getServerId() == myServerId){
                        continue;
                    }
                    userList.add(user);
                }
            }

            if(userList.size() > 0){
                RandomHelper randomHelper = new RandomHelper();
                int next = randomHelper.next(0, userList.size());
                UnionActivityGroupUser unionActivityGroupUser = userList.get(next);
                destServerId = unionActivityGroupUser.getServerId();
            }else {
                ret = GameErrorCode.E_CROSS_TRADE_WAR_ACTIVITY_SERVER_LIST_ERROR;
                return;
            }
        }else if(eTradeWarBattleType.Challenge.getValue() == battleType || eTradeWarBattleType.FightBack.getValue() == battleType){
            if(!activityInfo.getServerIdList().contains(enemyServerId)){
                ret = GameErrorCode.E_CROSS_TRADE_WAR_ACTIVITY_ENEMY_SERVER_ERROR;
                return;
            }
            destServerId = enemyServerId;
        }else if(eTradeWarBattleType.Track.getValue() == battleType){
            if(!activityInfo.getServerIdList().contains(enemyServerId)){
                ret = GameErrorCode.E_CROSS_TRADE_WAR_ACTIVITY_ENEMY_SERVER_ERROR;
                return;
            }
            ret = CrossTradeWarMgr.canCrossTrack(activityId, battleUid, myUserId, myServerId, true, dailyTrackTimes, limitTrackTimes, myUnionId);
            destServerId = enemyServerId;
        }else {
            ret = GameErrorCode.E_CROSS_TRADE_WAR_ACTIVITY_BATTLE_TYPE_ERROR;
            return;
        }
        CrossTradeWarProto.CrossTradeWarPrepareReqMsg.Builder msg = CrossTradeWarProto.CrossTradeWarPrepareReqMsg.newBuilder();
        msg.setActivityId(activityId);
        msg.setBattleType(battleType);
        msg.setMyUserId(myUserId);
        msg.setMyServerId(myServerId);
        msg.addAllPatronsIdList(patronsIdList);
        msg.setEnemyUserId(enemyUserId);
        msg.setEnemyServerId(enemyServerId);
        msg.setBattleUid(battleUid);
        msg.setUseItemId(useItemId);
        msg.setFastTeamNum(fastTeamNum);
        msg.setMyUnionId(myUnionId);
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_CROSS_TRADE_WAR_PREPARE_QUERY, msg);
        MessageHelper.sendPacket(destServerId, 0, pbMsg);
    }

    @Override
    public void sendData() {
        if(0 != ret) {
            CrossTradeWarProto.CrossTradeWarPrepareRespMsg.Builder respMsg = CrossTradeWarProto.CrossTradeWarPrepareRespMsg.newBuilder();
            respMsg.setActivityId(activityId);
            respMsg.setMyUserId(myUserId);
            respMsg.setMyServerId(myServerId);
            respMsg.setRet(ret);
            respMsg.setBattleType(battleType);
            respMsg.setMyUnionId(myUnionId);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_CROSS_TRADE_WAR_PREPARE_NOTIFY, respMsg);
            MessageHelper.sendPacket(myServerId, myUserId, pbMsg);
        }
    }
}
